<template>
    <x-popup v-model="showPopup" @hide="setAction('pay')" top="40vh" :auto-hide-tab-bar="props.autoHideTabBar">
        <view class="flex flex-center px-4">
            <view class="w-30px flex flex-center h-30px">
                <uni-icons type="bottom" size="20" color="var(--xl-placeholder)" @tap="setAction('pay')"
                    v-if="action === 'payTypeList'"></uni-icons>
            </view>
            <view class="flex-1 h8 font-weight-600 py-10 text-center"></view>
            <view class="flex flex-center" v-if="['vip'].includes(payInfo.type)" @tap="handleClickVip">
                <uni-icons type="vip-filled" class="vip-icon" size="16" color="var(--xl-4C402E)"></uni-icons>
                <view class="h9 text-4C402E font-weight-600 py-4 pr-4 pl-2">{{ WEBCONFIG?.vip_name }}</view>
            </view>
        </view>
        <view class="flex-1 flex overflow-auto flex-column flex-x-center" v-if="action === 'pay'">
            <view class="text-center text-white">{{ payInfo.title }}</view>
            <view class="h1 font-weight-600 text-center py-10 border-bottom border-bottom-grey text-primary">￥ {{ payInfo.price }}</view>
            <view class="flex p-4 flex-center h10 text-placeholder" @tap="setAction('payTypeList')">
                <view class="flex-1">付款方式</view>
                <view class="px-4 text-dark-light-2" v-if="payInfo.pay_type === 'wxpay'">微信</view>
                <view class="px-4 text-dark-light-2" v-else-if="payInfo.pay_type === 'alipay'">支付宝</view>
                <view class="px-4 text-dark-light-2" v-else-if="payInfo.pay_type === 'epay'">易支付</view>
                <view class="px-4 text-dark-light-2" v-else-if="payInfo.pay_type === 'dypay'">抖音支付</view>
                <uni-icons type="bottom" color="var(--xl-placeholder)" v-if="payTypeList.length > 1" />
            </view>
            <view class="py-10 flex flex-center">
                <view class="bg-primary text-white rounded-4 w-50 py-4 font-weight-600 text-center" @click="getpayInfo">支付</view>
            </view>
        </view>
        <view class="flex-1 flex overflow-auto flex-column p-10" v-else-if="action === 'payTypeList' && payTypeList.length > 0">
            <view class="h8 p-4 text-dark-light-2 bg-bg-grey rounded-4 mb-4" hover-class="bg-white"
                v-if="payTypeList.includes('wxpay')" @tap="setPayType('wxpay')">微信</view>
            <view class="h8 p-4 text-dark-light-2 bg-bg-grey rounded-4 mb-4" hover-class="bg-white"
                v-if="payTypeList.includes('dypay')" @tap="setPayType('dypay')">抖音支付</view>
            <!-- #ifdef H5 -->
            <view class="h8 p-4 text-dark-light-2 bg-bg-grey rounded-4 mb-4" hover-class="bg-white"
                v-if="payTypeList.includes('alipay')" @tap="setPayType('alipay')">支付宝</view>
            <view class="h8 p-4 text-dark-light-2 bg-bg-grey rounded-4 mb-4" hover-class="bg-white"
                v-if="payTypeList.includes('epay')" @tap="setPayType('epay')">易支付</view>
            <!-- #endif -->
        </view>
        <view class="flex-1 flex overflow-hidden flex-center" v-else-if="action === 'payTypeList' && payTypeList.length <= 0">
            <view class="h4 font-weight-600 p-4 text-dark-light-2">暂无可用支付方式</view>
        </view>
        <view class="pb-safe-area">
            <view class="py-4">
                <view class="flex flex-center">
                    <view class="h10 text-placeholder">请仔细阅读</view>
                    <view class="h10 text-primary ml-2" @tap="$page.open('/pages/article/content?alias=pay_agreement')">
                        《支付协议》</view>
                </view>
            </view>
        </view>
    </x-popup>
</template>

<script lang="ts" setup>
import { $http, $message, $page, $system } from '@/utils';
import { onMounted, ref, defineProps } from "vue";
import { useWebConfigStore, useRefs } from "@/stores";
const props = withDefaults(defineProps<{
    autoHideTabBar?: boolean,
}>(), {
});
const webConfigStore = useWebConfigStore();
const { WEBCONFIG } = useRefs(webConfigStore);
const showPopup = ref(false);
const emit = defineEmits(['success', 'Vip']);
const payInfo = ref<{
    type?: string,
    pay_type?: string,
    alias_id?: number,
    title?: string,
    price?: number | string,
    platform?: string,
    num?: number,
}>({
    pay_type: '',
    num: 1
});
const payTypeList = ref<string[]>([]);
const initPayType=()=>{
    if(payInfo.value.pay_type)return;
    // #ifdef H5
    if (WEBCONFIG.value?.wxpay_state && $system.isWechat()) {
        payTypeList.value.push('wxpay')
        payInfo.value.pay_type = 'wxpay'
    }
    if (WEBCONFIG.value?.alipay_state) {
        payTypeList.value.push('alipay')
        if (!payInfo.value.pay_type) {
            payInfo.value.pay_type = 'alipay'
        }
    }
    if (WEBCONFIG.value?.epay_state) {
        payTypeList.value.push('epay')
        if (!payInfo.value.pay_type) {
            payInfo.value.pay_type = 'epay'
        }
    }
    payInfo.value.platform = 'h5'
    // #endif
    // #ifdef MP-WEIXIN
    if (WEBCONFIG.value?.wxpay_state) {
        payTypeList.value.push('wxpay')
        payInfo.value.pay_type = 'wxpay'
    }
    payInfo.value.platform = 'mp-weixin'
    // #endif
    // #ifdef MP-TOUTIAO
    if (WEBCONFIG.value?.wxpay_state) {
        payTypeList.value.push('dypay')
        payInfo.value.pay_type = 'dypay'
    }
    payInfo.value.platform = 'mp-toutiao'
    // #endif
}

const data = ref<any>({});
const show = (options: any) => {
    initPayType();
    showPopup.value = true;
    payInfo.value.type = options.type;
    payInfo.value.alias_id = options.alias_id;
    payInfo.value.title = options.title;
    payInfo.value.price = options.price;
    data.value = options.data
}
const OrderStateNum = ref(0);
let OrderInfo: any = {};
const onBridgeReady = () => {
    WeixinJSBridge.invoke('getBrandWCPayRequest', OrderInfo.pay, (res: any) => {
        if (res.err_msg == "get_brand_wcpay_request:ok") {
            showPopup.value = false;
            OrderStateNum.value = 1;
            uni.showLoading({
                title: '查询中...',
                mask: true
            });
            getOrderState();
        }
    });
}
const getpayInfo = () => {
    uni.showLoading({
        title: '获取订单中...',
        mask: true
    });
    $http.post('Orders/create', {
        data: payInfo.value
    }).then((res: any) => {
        uni.hideLoading();
        if (res.code === $http.ResponseCode.SUCCESS) {
            OrderInfo = res.data;
            switch (payInfo.value.pay_type) {
                case 'wxpay':
                    // #ifdef H5
                    if (typeof WeixinJSBridge == "undefined") {
                        if (document.addEventListener) {
                            document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
                        } else if (document.attachEvent) {
                            document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
                            document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
                        }
                    } else {
                        onBridgeReady();
                    }
                    // #endif
                    // #ifdef MP-WEIXIN
                    uni.requestPayment({
                        provider: 'wxpay',
                        timeStamp: OrderInfo.pay.timeStamp,
                        nonceStr: OrderInfo.pay.nonceStr,
                        package: OrderInfo.pay.package,
                        signType: OrderInfo.pay.signType,
                        paySign: OrderInfo.pay.paySign,
                        orderInfo: OrderInfo.orderInfo,
                        success: (res: any) => {
                            showPopup.value = false;
                            OrderStateNum.value = 1;
                            uni.showLoading({
                                title: '查询中...',
                                mask: true
                            });
                            getOrderState();
                        },
                        fail: (err: any) => {
                            $message.error('支付失败');
                        }
                    });
                    // #endif
                    break;
                case 'dypay':
                    tt.pay({
                        orderInfo: OrderInfo.pay,
                        service:5,
                        success: (res: any) => {
                            showPopup.value = false;
                            OrderStateNum.value = 1;
                            uni.showLoading({
                                title: '查询中...',
                                mask: true
                            });
                            getOrderState();
                        },
                        fail: (err: any) => {
                            console.log(err)
                        }
                    })
                    break;
                case 'alipay':
                case 'epay':
                    // #ifdef H5
                    window.location.href = OrderInfo.pay_url;
                    // #endif
                    break;
            }
        } else {
            $message.error(res.msg);
        }
    }).catch(() => {
        uni.hideLoading();
        $message.error('获取支付信息失败');
    })
}
const action = ref('pay');
const setAction = (val: string) => {
    action.value = val;
}
const setPayType = (val: string) => {
    payInfo.value.pay_type = val;
    action.value = 'pay';
}
onMounted(() => {
})
const getOrderState = () => {
    $http.get('Orders/getOrderState', {
        data: {
            trade: OrderInfo.order.trade
        }
    }).then((res: any) => {
        if (res.code === $http.ResponseCode.SUCCESS) {
            $message.success('支付成功');
            emit('success', data.value);
            uni.hideLoading();
        } else if (res.code === $http.ResponseCode.PAY_NOTPAY) {
            OrderStateNum.value++;
            if (OrderStateNum.value > 10) {
                uni.hideLoading();
                $message.error('支付失败');
                return;
            }
            setTimeout(getOrderState, 1000)
        }
    }).catch(() => {
    })
}
const handleClickVip = () => {
    showPopup.value = false;
    emit('Vip');
}
defineExpose({ show });
</script>

<style lang="scss" scoped>
.w-30px {
    width: 30px;
}

.h-30px {
    height: 30px;
}

.vip-icon {
    width: 20px;
    height: 20px;
    animation: vip 1s infinite;
}

@keyframes vip {
    0% {
        transform: scale(1) rotate(0deg);
    }

    50% {
        transform: scale(1.5) rotate(-25deg);
    }

    100% {
        transform: scale(1) rotate(0deg);
    }
}</style>